package top.blacknota.service;

import top.blacknota.dao.NDao;
import top.blacknota.pojo.User;
import top.blacknota.utils.LpUtil;
import top.blacknota.utils.exception.LpException;

import java.util.List;

/**
 * Created by 撒哈拉来的企鹅 on 2018-2-8.
 */
public class UserService {

    NDao dao = NDao.getInstance();

    public User login(String username, String password) throws LpException {
        User user = dao.getUser(username);
        if (null == user) {
            throw new LpException("用户不存在");
        }
        System.out.println(password+":::::"+user.getPasshash());
        if (LpUtil.checkpw(password, user.getPasshash())){
            return user;
        }else {
            throw new LpException("密码错误");
        }
    }

    public List<User> allUsers() throws LpException {
        return dao.getAllUser();
    }

    public void addUser(User user) throws LpException {
        if(dao.findUserByName(user.getUsername())!=null){
            throw new LpException("用户名已存在");
        }
        try {
            user.setPassword(user.getPasshash());
            dao.addUser(user);
        }catch (Exception e){
            throw new LpException(e.toString());
        }
    }

    public void deleteUser(String userId) throws LpException{
        dao.deleteUser(userId);
    }

    public User findUserById(String userId) {
        return dao.findUserById(userId);
    }

    public void editUser(User user) throws LpException {
        if(dao.findUserById(user.getId())==null){
            throw new LpException("用户名ID错误");
        }
        try {
            if (user.getPasshash()==null||"".equals(user.getPasshash())){
                dao.editUserExPwd(user);
            }else {
                user.setPassword(user.getPasshash());
                dao.editUser(user);
            }
        }catch (Exception e){
            throw new LpException(e.toString());
        }
    }
}
